home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: Question on 'bubble sort'
- Date: Tue, 02 Apr 96 12:22:29 GMT
- Organization: none
- Message-ID: <828447749snz@genesis.demon.co.uk>
- References: <4jieso$juc@lantana.singnet.com.sg> <828206958snz@genesis.demon.co.uk> <4jmv0d$t2p@news1.mnsinc.com> <4jp8mnINNmq0@keats.ugrad.cs.ubc.ca>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <4jp8mnINNmq0@keats.ugrad.cs.ubc.ca>
- c2a192@ugrad.cs.ubc.ca "Kazimir Kylheku" writes:
-
- >In article <4jmv0d$t2p@news1.mnsinc.com>,
- >Szu-Wen Huang <huang@mnsinc.com> wrote:
- > >Lawrence Kirby (fred@genesis.demon.co.uk) wrote:
- > >: In article <4jieso$juc@lantana.singnet.com.sg>
- > >: s8700055@singnet.com.sg "XY Xie" writes:
- > >
- > >: >I came across this sorting algorithm called 'bubble sort' in a book.
- > >
- > >: If the book doesn't explain why there is never a good reason to use bubble
- > >: sort then I suggest you get another book.
- > >
- > >Sure there is. If I had 5 minutes to code something that will sort
- > >10 numbers, bubblesort comes in real handy. If you've ever joined
- > >a programming contest you'll know what I mean.
-
- You're still better off with insertion sort which is at least as simple.
-
- >It's also good for sorting a fixed number of points. Say I had to sort the
- >three vertices of a triangle in order of increasing y coordinate. What you do
- >is just compare the first two points, possibly swap, then the last two points,
- >possibly swap and then compare the first two points again, possibly swapping.
- >
- >This is just a special case of the bubble sort and I have used it in polygon
- >drawing code.
-
- Call it bubble sort if you will but that is also an insertion sort for
- 3 elements (at least if the 3rd test is conditional on the 2nd). The correct
- approach here is:
-
- if (a1 > a2)
- swap(&a1, &a2);
-
- if (a2 > a3) {
- swap(&a2, &a3);
-
- if (a1 > a2)
- swap(&a1, &a2);
- }
-
- which averages 2 2/3 comparisons for random data and is clearly an insertion
- sort for 3 elements.
-
- >The asymptotic complexity of algorithms matters little on any data set whose
- >size is fixed in advance, especially when the size is small. The precise size
- >at which the algorithm with better complexity surpasses the worse algorithm in
- >performance depends on the constants introduced by the implementation.
-
- Constant factors can still be important. You may have many triangles to
- calculate for.
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-